<template>
  <div class="wechat">
    <!-- 卡片视图区域 -->
    <div class="wechat_card">
      <!-- 布局 -->
      <el-row :gutter="20" class="wechat_card_head" type="flex">
        <el-col :span="8">
          <!-- 搜索框及添加区域 -->
          <el-input
            placeholder="请输入楼栋名"
            v-model="queryInfo.query"
            clearable
            @clear="getBuildList"
            @input="clearData"
            size="medium"
          >
            <el-button
              slot="append"
              size="medium"
              icon="el-icon-search"
              @click="getBuildList"
            ></el-button> </el-input
        ></el-col>
        <el-button
          size="medium"
          class="btn_head_medium"
          type="primary"
          @click="addDialogVisible = true"
          icon="el-icon-circle-plus-outline"
          >新增</el-button
        >

        <el-button
          class="btn_head_medium"
          size="medium"
          type="danger"
          @click="removeUserByIds"
          icon="el-icon-remove-outline"
          >删除</el-button
        >
        <div class="tools_head">
          <el-tooltip content="导出excel" placement="bottom">
            <el-button
              size="small"
              icon="el-icon-download"
              style="margin-left: 10px"
              @click="handleDownload"
            ></el-button>
          </el-tooltip>
        </div>
      </el-row>
      <!-- 楼栋列表区域 -->
      <el-table :data="buildList" style="width: 100%" border stripe :row-key="(row)=>{ return row.id}"
        tooltip-effect="dark"
        height="85%"
        size="small"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        ref="tableDataRef">
        <el-table-column type="selection" :reserve-selection="true"> </el-table-column>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="name" label="楼栋名"> </el-table-column>
        <el-table-column prop="state" label="状态">
          <template slot-scope="scope">
               <el-tooltip :content="scope.row.state==1?'使用中':'未使用'" placement="top">
                  <el-switch
                    v-model="scope.row.state"
                    :active-value="1"
                    :inactive-value="0"
                    @change="buildStateChanged(scope.row.id)"
                  >
                  </el-switch>
                </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150px">
          <!-- 作用域插槽 -->
          <template slot-scope="scope" >
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 详情按钮 -->
            <!-- <el-button
              type="success"
              icon="el-icon-s-order"
              size="mini"
            ></el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加楼栋的对话框 -->
      <el-dialog
        title="新增楼栋"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogReset"
      >
        <!-- 内容主题区域 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
        >
          <el-form-item label="楼栋名" prop="name"
            ><el-input v-model="addForm.name"></el-input
          ></el-form-item>
          <!-- <el-form-item label="小区名" prop="communityId"
            ><el-input v-model="addForm.communityId"></el-input
          ></el-form-item> -->
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addBuild">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改楼栋信息的对话框 -->
      <el-dialog
        title="修改楼栋信息"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
        <el-form
          ref="editFormRef"
          :model="editForm"
          label-width="100px"
          :rules="editFormules"
        >
          <el-form-item label="楼栋名" prop="name"
            ><el-input v-model="editForm.name"></el-input
          ></el-form-item>
          <!-- <el-form-item label="小区名" prop="communityId"
            ><el-input v-model="editForm.communityId"></el-input
          ></el-form-item> -->
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editBuild">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.queryInfo.pageNum"
        :page-sizes="[5, 30, 50, 100]"
        :page-size="this.queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  data() {
    return {
      // 获取楼栋列表的参数对象
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 5
      },
      buildList: [],
      total: 0,
      //选中行的id数组
      multipleSelection: [],
      idsArray:{
        ids:[]
      },
      // 控制添加对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改对话框的显示与隐藏
      editDialogVisible: false,
      // 添加楼栋的表单数据
      addForm: {
        name: '',
        state:''
      },
      // 查询到的编辑楼栋信息
      editForm: {},
      // 添加表单的验证规则对象
      addFormRules: {
        name: [
          { required: true, message: '请输入楼栋名', trigger: 'blur' }
        ],
        // communityId: [
        //   { required: true, message: '请输入小区名', trigger: 'blur' },
        // ]
      },
      // 修改楼栋信息表单的验证规则
      editFormules: {
        name: [
          { required: true, message: '请输入楼栋名', trigger: 'blur' }
        ],
        // communityId: [
        //   { required: true, message: '请输入小区名', trigger: 'blur' },
        // ]
      }

    }

  },
  created() {
    this.getBuildList()
  },
  methods: {
    // 获取楼栋列表
    async getBuildList() {
       if (this.queryInfo.query !== '')
        //模糊查楼栋号
        this.queryInfo.condition = `name like "%${this.queryInfo.query}%"`
      const { data: res } = await this.$http.get('BasefloorAction/getBasicInfos', { params: this.queryInfo })
      if (!res.success) return this.$message.error('获取楼栋列表失败')
      console.log(res)
      this.buildList = res.rows
      this.total = res.total
    },
     //监听搜索输入框
    clearData() {
      if (this.queryInfo.query == '') {
        delete this.queryInfo.condition
      }
    },
    //点击按钮，添加新楼栋记录
    addBuild() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        this.addForm.state = 0;
        const { data: res } = await this.$http.post("BasefloorAction/addObject", this.addForm)
        if (!res.success) return this.$message.error('添加楼栋记录失败')
        //关闭对话框
        this.addDialogVisible = false
        //刷新数据列表
        this.getBuildList()
        this.$message.success('添加楼栋记录成功')
      })
    },
    // 展示编辑楼栋记录的对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.post("BasefloorAction/getObjectById", { id })
      if (!res.success)
        return this.$message.error('查询楼栋记录失败')
      this.editForm = res.rows[0]
      // console.log(this.editForm);
      this.editDialogVisible = !this.editDialogVisible
    },

    //点击按钮，修改楼栋记录信息
    editBuild() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post("BasefloorAction/updateNoNull", this.editForm)
        if (!res.success) return this.$message.error('修改楼栋记录信息失败')
        //关闭对话框
        this.editDialogVisible = false
        //刷新数据列表
        this.getBuildList()
        this.$message.success('修改楼栋记录信息成功')
      })
    },
  
    // 根据id删除楼栋
    async removeUserById(ids) {
      // 先弹框询问用户是否确定要删除
      const confirmResult = await this.$confirm('此操作将永久删除该楼栋, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      // 如果点击取消返回的是字符串cancel
      // 如果点击确认返回的是字符串confirm
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.post("BasefloorAction/deleteByIds", { ids })
      console.log(res);
      if (!res.success) {
        return this.$message.error('删除楼栋记录失败')
      }
      this.$message.success('删除楼栋记录成功')
      // 刷新列表
      this.getBuildList()
    },

     //批量删除
    async removeUserByIds() {
      const rows = this.$refs.tableDataRef.selection;
      if (rows.length === 0) {
        this.$message.warning('请选择需要操作的数据')
        return
      }
      else {
        // 先弹框询问用户是否确定要删除
        const confirmResult = await this.$confirm('此操作将永久删除该楼栋记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => {
          return err
        })
        if (confirmResult !== 'confirm') {
          return this.$message.info('取消了删除')
        }
        const { data: res } = await this.$http.post("BasefloorAction/deleteByIds",  this.idsArray )
        console.log(res);
        if (!res.success) {
          return this.$message.error('删除楼栋记录失败')
        }
        this.$message.success('删除楼栋记录成功')
        //此时全选框还是选中状态，批量删除后需清除选中状态
        this.$refs.tableDataRef.clearSelection();
        // 刷新列表
        this.getBuildList()
      }

    },
     //当多选框选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.idsArray.ids = [] //每次点击需清空原本数组的内容
      this.multipleSelection.map(item => { //遍历数组，把id存进自定义的数组里
        this.idsArray.ids.push(item.id)
      })
      this.idsArray.ids = this.idsArray.ids.join(',')
      // console.log(this.idsArray);
      
    },
      //导出Excel表
    handleDownload(){
      window.open(axios.defaults.baseURL+'/BasefloorAction/exportDataToExcel?token='+window.sessionStorage.getItem('token'))
    },
    // 监听修改楼栋对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 监听pageSize改变的事件
    handleSizeChange(newPageSize) {
      // console.log(newPageSize)
      this.queryInfo.pageSize = newPageSize
      // PageSize改变重新拿到楼栋列表
      this.getBuildList()
    },
    // 监听当前页码改变的事件
    handleCurrentChange(newPageNum) {
      // console.log(newPageNum)
      this.queryInfo.pageNum = newPageNum
      this.getBuildList()
    },
    addDialogReset() {
      // 拿到表单的引用进行重置
      this.$refs.addFormRef.resetFields()
    },
    //监听switch开关状态的变化
    async buildStateChanged(id) {
      this.editForm.id = id 
      this.editForm.state = this.editForm.state>0?0:1
      const { data: res } = await this.$http.post("BasefloorAction/updateNoNull", this.editForm)
        if (!res.success) return this.$message.error('修改楼栋状态失败')
        //刷新数据列表
        this.getBuildList()
        this.$message.success('修改楼栋状态成功')
    }
  }
}
</script>
<style lang="less" scoped>
</style>